import info from "./index";
import userModel from "../model/useraxios"
let deluser=(payload:any)=>{
    return {
        type:info.DELUSER,
        payload:payload
    }
}
let inituserlist=(payload:any)=>{
    return {
        type:info.INITUSERLIST,
        payload
    }
}
let adduser=(payload:any)=>{
    return{
        type:info.ADDUSER,
        payload
    }
}
let asyncInitUserList = () => {

    // let  {data:list} = await  userModel.query({});//异步操作
    // initUserList(list); //同步操作 store.dispatch(initUserList(list))

    return async (dispatch: any) => {
        let { data: list } = await userModel.query({});
        dispatch(inituserlist(list));//触发带着action对象 去修改数据

    }

}
let asyncAddUserItem = (payload: any) => {

    return  (dispatch: any) => {

        return  new  Promise(async(resolve)=>{

            let { data: list } = await userModel.query({
                username: payload.username
            })
            if (list.length) {//存在

                resolve({
                    code:0,
                    msg:"该用户名已经存在"
                })
    
    
            } else {//新增
                let { data } = await userModel.add(payload);
                dispatch(adduser(data));

                resolve({
                    code:1,
                    msg:"新增成功"
                })
            }

        });

      

    }


}

let asyncDelUserById = (payload: number) => {

    return async (dispatch: any) => {
        await userModel.del(payload);//payload是id
        dispatch(deluser(payload));
    }

}



export {deluser,inituserlist,adduser,asyncInitUserList,asyncAddUserItem,asyncDelUserById}